package com.baibei.product.trade;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.res.ResourcesCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.model.Area;
import com.baibei.model.CouponInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.TradeTimeInfo;
import com.baibei.model.TradeType;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.AreaHelper;
import com.baibei.module.BasicActivity;
import com.baibei.module.stock.basic.BasicMinuteFragment;
import com.baibei.module.stock.basic.BasicStockFragment;
import com.baibei.module.stock.simple.SimpleStockFragment;
import com.baibei.product.R;
import com.baibei.product.R2;
import com.baibei.ui.AppUI;
import com.baibei.widget.JustifyTextView;
import com.bumptech.glide.Glide;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 订货界面
 * Created by ChenRui on 2017/8/7 0007 11:24.
 */
@Route(path = AppRouter.ROUTER_PRODUCT_TRADE)
public class TradeActivity extends BasicActivity implements TradeHomeContract.View, TradeFragment.OnTradeSuccessListener {

    @BindView(R2.id.btn_buy)
    TextView mBtnBuy;
    @BindView(R2.id.btn_sell)
    TextView mBtnSell;
    @BindView(R2.id.tv_stop_trade_time)
    TextView mTvStopTradeTime;
    @BindView(R2.id.tv_price_title)
    TextView mTvPriceTitle;
    private ProductInfo mProductInfo;
    private String mSaleTips;
    private long mEstimateTime;

    @BindView(R2.id.img_product)
    ImageView mProductView;

    @BindView(R2.id.img_product_flag)
    ImageView mProductFlagView;

    @BindView(R2.id.tv_title)
    TextView mTitleView;

    @BindView(R2.id.tv_number)
    TextView mNumberView;

    @BindView(R2.id.tv_time)
    TextView mTimeView;

    @BindView(R2.id.tv_price)
    TextView mPriceView;

    @BindView(R2.id.tv_open)
    TextView mOpenView;

    @BindView(R2.id.tv_close)
    TextView mCloseView;

    @BindView(R2.id.tv_high)
    TextView mHighView;

    @BindView(R2.id.tv_low)
    TextView mLowView;

    @BindView(R2.id.ll_bottom)
    View mBottomLayout;

    private TradeHomeContract.Presenter mPresenter;
    private TradeType mCurrentTradeType;
    private BasicStockFragment mStockFragment;

    /**
     * 今开 昨收
     */
    private double mClose;
    private double mOpen;
    private String helpContent;


    @Override
    public IPresenter getBasicPresenter() {
        return mPresenter;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trade);
        ButterKnife.bind(this);
        mPresenter = inject(TradeHomeContract.Presenter.class);
        mEstimateTime = getIntent().getLongExtra("estimateTime", 0);
        mProductInfo = getIntent().getParcelableExtra("productInfo");
        mSaleTips = getIntent().getStringExtra("saleTips");

        if (mProductInfo == null) {
            AppUI.failed(this, "产品不存在");
            finish();
            return;
        }

        onLoadProductInfo(mProductInfo);

        mStockFragment = SimpleStockFragment.newInstance(mProductInfo.getProductId());

        // 加载图表
        getSupportFragmentManager().beginTransaction().add(R.id.content, mStockFragment, "stock").commit();

        //加载基础数据，开休市，价格
        mPresenter.loadBasicData();
        mPresenter.getHelp();
    }


    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.loadBalanceAndCoupons();

        // 企业用户隐藏
        if (SessionManager.getDefault().isLogin()) {
            UserInfo user = SessionManager.getDefault().getUser();
            if (user.getUserType() == UserInfo.USER_TYPE_ENTERPRISE) {
                mBottomLayout.setVisibility(View.GONE);
            }
        }
    }

    private void onLoadProductInfo(ProductInfo m) {
        mTitleView.setText(m.getName());
        Glide.with(this).load(m.getProductPic()).into(mProductView);

        mProductFlagView.setImageResource(AreaHelper.getImageResource(Area.valueOf(m.getArea())));
        mNumberView.setText(m.getRepertoryStatus());

        //剩余促销时间显示问题
        if (mSaleTips.contains(":")) {
            int index = mSaleTips.indexOf(":") + 1;
            SpannableString spannableString = new SpannableString(mSaleTips);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FF303030")), 0, index, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#FFFF3B30")), index, mSaleTips.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            mTimeView.setText(spannableString);
        } else {
            mTimeView.setText(mSaleTips);
        }
    }

    private void showTradeDialog(TradeType type) {
        mCurrentTradeType = type;
        // 登录检查
        if (!SessionManager.getDefault().isLogin()) {
            AppRouter.routeToLoginJustReturn(this);
            return;
        }
        // 不允许企业用户
        UserInfo userInfo = SessionManager.getDefault().getUser();
        if (userInfo.getUserType() == UserInfo.USER_TYPE_ENTERPRISE) {
            AppRouter.routeToNotAllow(getContext());
            return;
        }
        // 余额检查
//        if (mPresenter.checkBalance()) {
//            new DialogBuilder(getContext())
//                    .setMessage("账户可用余额不足，前往充值？")
//                    .positiveButtonClickListener(new IAppDialogClickListener() {
//                        @Override
//                        public void onClick(IAppDialog dialog, int i) {
//                            dialog.dismiss();
//                            AppRouter.routeToRecharge(getContext());
//                        }
//                    })
//                    .show();
//            return;
//        }
        TradeFragment.newInstance(mProductInfo, type, mPresenter.getValidCouponList(), mPresenter.getSuggestNumbers(), mPresenter.getMaxDefindCount())
                .show(getSupportFragmentManager(), "trade");
    }

    @OnClick(R2.id.btn_product_detail)
    public void onProductDetailClick() {
        AppRouter.routeToProductDetail(this, mProductInfo);
    }

    @OnClick(R2.id.btn_buy)
    public void onBuyClick() {
        showTradeDialog(TradeType.BUY);
    }

    @OnClick(R2.id.btn_sell)
    public void onSellClick() {
        showTradeDialog(TradeType.SELL);
    }


    @Override
    public ProductInfo getProduct() {
        return mProductInfo;
    }

    @Override
    public void onEmptyPrice() {
        String def = getString(R.string.default_placeholder);
        mPriceView.setText(def); // 最新价格
        mOpenView.setText(def); // 今开
        mCloseView.setText(def); // 昨收
        mHighView.setText(def); // 最高
        mLowView.setText(def); // 最低
    }

    @Override
    public void onLoadProductPrice(QuotationInfo quotationInfo) {
        String def = getString(R.string.default_placeholder);

        //记录今开昨收，用于推送比较
        mClose = quotationInfo.getPreClose();
        mOpen = quotationInfo.getOpen();

        mOpenView.setText(quotationInfo.getOpen() == 0 ? def : Rx.formatPrice(quotationInfo.getOpen())); // 今开
        mCloseView.setText(quotationInfo.getPreClose() == 0 ? def : Rx.formatPrice(quotationInfo.getPreClose())); // 昨收
        upDateProductPrice(quotationInfo);

        // 发送消息
        if (mStockFragment != null && mStockFragment.getMinuteFragment() != null) {
            BasicMinuteFragment minuteFragment = mStockFragment.getMinuteFragment();
            minuteFragment.setClosePrice(361.21);
        }

    }

    @Override
    public void upDateProductPrice(QuotationInfo quotationInfo) {
        mPriceView.setText(Rx.formatPrice(quotationInfo.getLast())); // 最新价格
        //颜色设置--最新价低于昨收应该绿色显示，等于昨收为黑色，大于昨收才为红色。
        int color;
        double price = mClose != 0 ? mClose : mOpen;
        if (quotationInfo.getLast() < price) {
            color = R.color.sellColor;
        } else if (quotationInfo.getLast() > price) {
            color = R.color.buyColor;
        } else {
            color = R.color.textPrimary;
        }
        mPriceView.setTextColor(ResourcesCompat.getColor(getResources(), color, null));
        String def = getString(R.string.default_placeholder);
        mHighView.setText(quotationInfo.getHigh() == 0 ? def : Rx.formatPrice(quotationInfo.getHigh())); // 最高
        mLowView.setText(quotationInfo.getLow() == 0 ? def : Rx.formatPrice(quotationInfo.getLow())); // 最低
    }

    @Override
    public void onLoadCoupons(List<CouponInfo> couponInfos) {
        //显示此商品是否有体验券可用
//        if (true){
        if (!Rx.isEmpty(couponInfos)) {
            mTitleView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_coupon, 0);
        }
    }

    @Override
    public void onLoadTradeTimeInfo(TradeTimeInfo info) {
        //按钮是否置灰
        mBtnBuy.setEnabled(info.getFlag() == 1);
        mBtnSell.setEnabled(info.getFlag() == 1);

        //显示休市中
        mTvStopTradeTime.setVisibility(info.getFlag() == 1 ? View.GONE : View.VISIBLE);
        mTvPriceTitle.setVisibility(info.getFlag() == 1 ? View.VISIBLE : View.INVISIBLE);
        mPriceView.setVisibility(info.getFlag() == 1 ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    public void onLoadHelpSuccess(String s) {
        helpContent = s;
    }

    @Override
    protected void onActivityResultOK(int requestCode, Intent data) {
        super.onActivityResultOK(requestCode, data);
        if (requestCode == AppRouter.REQ_LOGIN && mCurrentTradeType != null) {
            if (mCurrentTradeType == TradeType.BUY)
                onBuyClick();
            else
                onSellClick();
        }
    }

    @Override
    public void onTradeSuccess() {
        //成功后跳转到订货页面
        AppRouter.routeToOrderCenter(this);
        finish();
    }

    @OnClick(R2.id.iv_help)
    public void onHelpClicked() {
        popHelpDialog();
    }

    private void popHelpDialog() {
        Dialog helpDialog = new Dialog(this,R.style.HelpDialog);
        Window window = helpDialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setDimAmount(0f);
        window.setGravity(Gravity.RIGHT | Gravity.TOP);
        helpDialog.setContentView(R.layout.dialog_pop_help);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.x = dip2px(this, 27);
        lp.y = dip2px(this, 39);
        JustifyTextView tvHelp = helpDialog.findViewById(R.id.tv_help);
        tvHelp.setText(helpContent+"\n");
//        tvHelp.setText("\n1.  不支持持单过夜，凌晨2点将自动退订\n\n"+
//                "2.  每种规格的商品只能持单1笔，需退订后才可建新单\n\n" +
//                "3.  投资有风险，交易须谨慎，降低风险止盈止损范围（0-90%）\n");
        helpDialog.show();
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @OnClick(R2.id.img_full_screen)
    public void onFullScreenClicked() {
        AppRouter.routeToKLine(this, mProductInfo.getProductId());

    }
}
